/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.services.RMPService;
import com.apps.services.factory.RMPServiceFactory;
import com.apps.ubc.cc.model.RMPModel;
import com.apps.utils.UrlEncodingUtils;

public class RMPController extends HttpServlet {

	RMPService rs = RMPServiceFactory.getRMPService();

	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String instructors = req.getParameter("instructors");
		instructors = UrlEncodingUtils.decodeURL(instructors);
		List<RMPModel> rml = rs.getProfInfo(instructors);
		StringBuilder builder=new StringBuilder();
		builder.append("<rmp>\n");
		//String out = "<rmp>\n";
		for (Iterator<RMPModel> i = rml.iterator(); i.hasNext();) {
			RMPModel rm = i.next();
			builder.append("\t<instructor>\n");
			//out += "\t<instructor>\n";
			if(rm.getName().isEmpty())
				builder.append( "\t\t<name>Not available</name>\n");
				//out += "\t\t<name>Not available</name>\n";
			else
				builder.append("\t\t<name>" + rm.getName() + "</name>\n");
				//out += "\t\t<name>" + rm.getName() + "</name>\n";
			builder.append("\t\t<rating>" + rm.getRating() + "</rating>\n");
			//out += "\t\t<rating>" + rm.getRating() + "</rating>\n";
			builder.append("\t\t<url>" + rm.getUrl() + "</url>\n");
			builder.append("\t</instructor>\n");
//			out += "\t\t<url>" + rm.getUrl() + "</url>\n";
//			out += "\t</instructor>\n";
		}
		if (rml.size() == 0){
			builder.append("\t<instructor>\n");
			builder.append("\t\t<name>Not available</name>\n");
			builder.append("\t\t<rating>not found</rating>\n");
			builder.append("\t\t<url>not found</url>\n");
			builder.append("\t</instructor>\n");
//			out += "\t<instructor>\n";
//			out += "\t\t<name>Not available</name>\n";
//			out += "\t\t<rating>not found</rating>\n";
//			out += "\t\t<url>not found</url>\n";
//			out += "\t</instructor>\n";
		}
		builder.append("</rmp>");
		//out += "</rmp>";
		try {
			resp.setContentType("text/xml");
			resp.getWriter().write(builder.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
